package com.rainsoftware.LicenseSystem.services;

import com.rainsoftware.LicenseSystem.models.entity.LicenseKey;
import com.rainsoftware.LicenseSystem.models.entity.Product;
import com.rainsoftware.LicenseSystem.models.entity.SystemUser;
import com.rainsoftware.LicenseSystem.utils.MD5Generator;
import com.rainsoftware.LicenseSystem.utils.StandardResponse;
import gaarason.database.appointment.OrderBy;
import gaarason.database.contract.eloquent.Builder;
import gaarason.database.contract.eloquent.Record;
import gaarason.database.contract.eloquent.RecordList;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.http.HttpStatus;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ProductService {

    @Autowired
    private Product.Model productModel;

    @Autowired
    private LicenseKey.Model licenseKeyModel;

    @Autowired
    private SystemUser.Model sysUserModel;

    @Autowired
    UserService userService;

    public void deleteKeys(List<Integer> productIDs) {
        RecordList<LicenseKey, Integer> keyRecords = licenseKeyModel.newQuery()
                .whereIn("product_id", productIDs).get();
        for (Record<LicenseKey, Integer> key : keyRecords) {
            key.delete();
        }
    }

    public StandardResponse createProduct(String productName) {
        int devID = userService.getSystemUser().getId();
        Record<SystemUser, Integer> userRecord = sysUserModel.newQuery().where("id", devID).first();
        if (userRecord == null) {
            return new StandardResponse(false, HttpStatus.BAD_REQUEST, "开发者不存在", null);
        }
        if (productModel.newQuery().where("name", productName).where("developer_id", devID).first() != null) {
            return new StandardResponse(false, HttpStatus.BAD_REQUEST, "产品已经存在", null);
        }

        Record<Product, Integer> productRecord = productModel.newRecord();
        Product product = productRecord.getEntity();
        product.setName(productName);
        product.setDeveloperId(devID);

        // 生成 API ID
        String apiID = MD5Generator.get(productName + "|" + LocalDateTime.now());
        product.setApiId(apiID);
        productRecord.save();

        return new StandardResponse(true, HttpStatus.OK, "产品创建成功",
                new JSONObject().put("id", product.getId())
                        .put("name", product.getName())
                        .put("created_at", product.getTimeCreated())
                        .put("api_id", product.getApiId()));
    }

    public StandardResponse getProductList(int limit) {
        int devID = userService.getSystemUser().getId();

        Builder<Product, Integer> builder = productModel.newQuery().where("developer_id", devID);
        if (limit > 1) {
            builder = builder.orderBy("created_at", OrderBy.DESC).limit(limit);
        }
        RecordList<Product, Integer> productRecords = builder.get();

        JSONArray array = new JSONArray();
        for (Record<Product, Integer> record : productRecords) {
            array.put(new JSONObject()
                    .put("id", record.getEntity().getId())
                    .put("name", record.getEntity().getName())
                    .put("api_id", record.getEntity().getApiId())
                    .put("created_at", record.getEntity().getTimeCreated())
                    .put("activation_count", record.getEntity().getActivationCount())
                    .put("key_count", record.getEntity().getKeyCount())
            );
        }
        return new StandardResponse(true, HttpStatus.OK, "获取成功", new JSONObject().put("products", array));
    }

    public StandardResponse deleteMultipleProducts(List<Integer> array) {
        if (array == null || array.isEmpty()) {
            return new StandardResponse(false, HttpStatus.BAD_REQUEST, "产品不能为空");
        }
        int devID = userService.getSystemUser().getId();

        // Get the list of products that belong to the developer
        RecordList<Product, Integer> productRecords = productModel.newQuery()
                .where("developer_id", devID)
                .whereIn("id", array)
                .get();

        Record<Product, Integer> record = productModel.newQuery()
               .where("developer_id", devID)
               .whereIn("id", array)
               .first();


        if (record == null) {
            return new StandardResponse(false, HttpStatus.BAD_REQUEST, "产品不存在或没有权限删除");
        }

        if (productRecords.size() != array.size()) {
            return new StandardResponse(false, HttpStatus.BAD_REQUEST, "一些产品不存在或没有权限删除");
        }

        // Delete each product
        for (Record<Product, Integer> productRecord : productRecords) {
            productRecord.delete();
        }

        // 同时删除相关的产品密钥
        deleteKeys(array);

        return new StandardResponse(true, HttpStatus.OK, "产品批量删除成功", null);
    }
}